package com.sgcc.pda.mdrh.task.safe.ui.ac;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.cepri.service.yingxiao.baidutts.BaiduTtsManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgcc.pda.baselibrary.utils.JsonUtil;
import com.sgcc.pda.baselibrary.utils.ToastUtils;
import com.sgcc.pda.common.aidl.CommonCallback;
import com.sgcc.pda.common.aidl.CommonResults;
import com.sgcc.pda.h5.businessHw.LableUHFBinderUtil;
import com.sgcc.pda.h5.db.DBH5BinderUtil;
import com.sgcc.pda.h5.dialog.DialogH5Util;
import com.sgcc.pda.mdrh.h5.jsbridge.MixCallHandler;
import com.sgcc.pda.mdrh.h5.jsbridge.MixRegisterHandler;
import com.sgcc.pda.mdrh.h5.jsbridge.MixWebChromeClient;
import com.sgcc.pda.mdrh.h5.library.BridgeWebView;
import com.sgcc.pda.mdrh.h5.library.CallBackFunction;
import com.sgcc.pda.mdrh.h5.library.DefaultHandler;
import com.sgcc.pda.mdrh.task.safe.R;
import com.sgcc.pda.mdrh.task.safe.jsbridge.MdrhH5Widget;
import com.sgcc.pda.mdrh.utils.BitmapUtil;
import com.sgcc.pda.mdrh.utils.FileUtils;
import com.sgcc.pda.sdk.utils.DateUtil;
import com.sgcc.pda.sdk.utils.SharePrefUtil;
import com.sgcc.pda.sdk.utils.StatusBarUtil;
import com.tencent.smtt.sdk.WebView;
import com.watermark.androidwm.Watermark;
import com.watermark.androidwm.WatermarkBuilder;
import com.watermark.androidwm.bean.WatermarkText;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 支持H5项目的webview页面
 */
public class MixWebViewActivity extends AppCompatActivity {

    public static final String WEB_URL = "webUrl";

    private static final String TAG = "MixWebViewActivity";
    BridgeWebView mWebView;
    private CallBackFunction getPhotoFunction;
    private MdrhH5Widget mdrhH5Widget;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        initView();
        initData();
    }

    protected void initView() {
        mWebView = findViewById(R.id.webView);
        mdrhH5Widget = new MdrhH5Widget();
        mdrhH5Widget.onCreate(this);
        // 设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StatusBarUtil.setColorRes(this, R.color.bg_gr);
            StatusBarUtil.setTextColor(this, true);
        } else {
            StatusBarUtil.setColorRes(this, R.color.tv_a3);
        }
    }

    protected void initData() {
        //java调用js
        MixCallHandler.getInstance().registBridgeView(mWebView);
        initLableUHF();
        //弹窗
        DialogH5Util.getInstance().init(this);

        Intent intent = getIntent();
        String web_url = intent.getStringExtra(WEB_URL);
        if (!TextUtils.isEmpty(web_url)) {
            initWebView(web_url, intent);
        }
    }

    /**
     * 初始化 蓝牙超高频标签
     */
    private void initLableUHF() {
        //蓝牙超高频通信
        LableUHFBinderUtil.getInstance().initBluetooth(null, new CommonCallback() {
            @Override
            public void callback(CommonResults commonResults) {
                commonResults.getResults();
                MixCallHandler.getInstance().javaToJsCallback("connect", commonResults);
            }
        });
    }


    /**
     * 初始化webview
     *
     * @param web_url
     */
    private void initWebView(String web_url, Intent intent) {
        DialogH5Util.getInstance().showLoading("加载中...");
        //webView初始化
        mWebView.setDefaultHandler(new DefaultHandler());
        mWebView.setWebChromeClient(new MixWebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.d(TAG, "H5加载进度: " + newProgress);
                if (newProgress >= 100) {
                    DialogH5Util.getInstance().hideLoading();
                }
                super.onProgressChanged(view, newProgress);
            }
        });

        if (!TextUtils.isEmpty(web_url)) {
            if (web_url.contains("http://") || web_url.contains("https://")) {
                //此处增加http的判断，主要是为了业务方便本地调试
                mWebView.loadUrl(web_url);
            } else {
                mWebView.loadUrl("file:///" + web_url);
            }
        } else {
            ToastUtils.show(this, "url地址为空");
        }

        // 注册js调用java的接口
        MixRegisterHandler.getInstance().submitFromWeb(mWebView);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK) {
            //h5每次传递的function对象都不是相同的一个,所以每次都必须重新赋值
            getPhotoFunction = MixRegisterHandler.getInstance().getGetPhotoFunction();
            if (getPhotoFunction != null) {
                getPhotoFunction.onCallBack(getImageJson(data));
            }
        }else if (requestCode == 1234) {
            MixRegisterHandler.getInstance().faceFecognition(data);
        }
    }

    // 使用Webview的时候，返回键没有重写的时候会直接关闭程序，这时候其实我们要其执行的知识回退到上一步的操作
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //这是一个监听用的按键的方法，keyCode 监听用户的动作，如果是按了返回键，同时Webview要返回的话，WebView执行回退操作，因为mWebView.canGoBack()返回的是一个Boolean类型，所以我们把它返回为true
        //webview.canGoBack()只有在非index网页时候，才返回true，否则返回false
        //webview加载网页失败时，webview.canGoBack也是返回false
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mdrhH5Widget.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mdrhH5Widget.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//			//此处，需要将所有操作数据库的map清空
        DBH5BinderUtil.getInstance().closeAllSqliteHelper();
        DialogH5Util.getInstance().hideLoading();
        LableUHFBinderUtil.getInstance().unRegisterBluetoothReceiver();
        mdrhH5Widget.onDestroy(this);
        //释放tts资源
        BaiduTtsManager.getInstance().release();
    }

    /**
     * 获取图片
     *
     * @param data 相册或者相机返回结果数据
     */
    private String getImageJson(Intent data) {
        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
        List<String> images = new ArrayList<>();
        List<String> videos = new ArrayList<>();
        for (LocalMedia localMedia : selectList) {
            if (PictureMimeType.isPictureType(localMedia.getPictureType()) == 1) {
//                Bitmap bitmap = BitmapFactory.decodeFile(localMedia.getPath());
                Bitmap bitmap = FileUtils.convertToBitmap(localMedia.getPath());
                String wtNo = SharePrefUtil.getString(this, "wtNo", "");
                WatermarkText watermarkText1 = new WatermarkText("工作票：" + wtNo)
                        .setPositionX(0.30)
                        .setPositionY(0.85)
                        .setTextColor(Color.BLACK)
                        .setTextShadow(0.3f, 3, 3, Color.GRAY)
                        .setTextAlpha(400)
                        //.setRotation(10)
                        .setTextSize(14);

                String timeStr = "时间：" + DateUtil.get2YTime();
                WatermarkText watermarkText2 = new WatermarkText(timeStr)
                        .setPositionX(0.30)
                        .setPositionY(0.90)
                        .setTextColor(Color.BLACK)
                        .setTextShadow(0.3f, 3, 3, Color.GRAY)
                        .setTextAlpha(400)
                        //.setRotation(10)
                        .setTextSize(14);
//               String tion = GisManager.getInstance(this).getLastValidLocation();

//                WatermarkText watermarkText3 = new WatermarkText("测试 3")
//                        .setPositionX(0.50)
//                        .setPositionY(0.90)
//                        .setTextColor(Color.WHITE)
//          ad              .setTextShadow(0.3f, 3, 3, Color.GRAY)
//                        .setTextAlpha(400)
//                        //.setRotation(10)
//                        .setTextSize(14);
                final List<WatermarkText> watermarkTexts = new ArrayList<>();
                if (!TextUtils.isEmpty(wtNo)) {
                    watermarkTexts.add(watermarkText1);
                }
                watermarkTexts.add(watermarkText2);
//                watermarkTexts.add(watermarkText3);
                Watermark mark = WatermarkBuilder.create(this, bitmap)
                        .loadWatermarkTexts(watermarkTexts)
                        .getWatermark();
                Bitmap bitmap2 = mark.getOutputImage();
                //压缩图片并转化为 base64
                String tempFileName = System.currentTimeMillis() + ".jpg";
                String filePath = localMedia.getPath().substring(0, localMedia.getPath().lastIndexOf("/"));
                boolean isSave = BitmapUtil.saveBitmap(tempFileName, filePath, bitmap2, this);
                if (isSave) {
                    String tempWaterFile = filePath + File.separator + tempFileName;
                    String imgBase64 = FileUtils.compressImageFile(this, tempWaterFile);
                    if (!imgBase64.equals("图片压缩失败") && !imgBase64.equals("原图已损坏")) {
                        images.add(imgBase64);
                        FileUtils.deleteFile(new File(tempWaterFile));
                    } else {
                        ToastUtils.show(this, imgBase64);
                    }
                }else {
                    ToastUtils.show(this, "保存水印图片失败");
                }
            } else if (PictureMimeType.isVideo(localMedia.getPictureType())) {
                videos.add(localMedia.getPath());
            }
        }
        CommonResults results = new CommonResults("1", "success");
        results.addResult("images", images);
        results.addResult("videos", videos);
        String json = JsonUtil.beanToString(results, CommonResults.class);
        return json;
    }
}